<?php
require_once 'models/acl.inc';
require_once 'common/mvpEvents.inc';
require_once 'services/TIntrinsicPageService.inc';
require_once 'models/TCMSCategoryModel.inc';
require_once 'models/TCMSPageModel.inc';

class TMSFrontPageItem implements IItem {
/**
 * @var TCandyItem
 */	
	protected $base;
/**
 * @var TMSFrontPage
 */	
	protected $page;
	
	public function __construct(TCandyItem $base, TMSFrontPage $page){
		$this->base = $base;
		$this->page = $page;
	}
	
	public function __get($nm){
		switch ($nm){
			case 'Link':return $this->page->ItemUrl($this->base);break;
			case 'IsCurrent':return $this->page->IsParentItem($this);break;
			default:return $this->base->$nm;break;
		}
	}
	
	public function ItemId(){
		return $this->base->ItemId();
	}
	
	public function ClassName(){
		return $this->base->ClassName();
	}
	
	public function __toString(){
		return (string)$this->base;
	}
	
	public function Properties($includetypes = array(),$excludetypes = array()){
		return $this->base->Properties($includetypes, $excludetypes);
	}
	public function Property($name){
		return $this->base->Property($name);
	}
	
	public function Contents(){
		return new TMSFrontPageItemIterator($this->base->Contents(),$this->page);
	}
	
	public function Subs(){
		return $this->page->CategoryPages($this->base->Slug);
	}
}

class TMSFrontPageItemIterator extends TIteratorAdapter {
/**
 * @var TMSFrontPage
 */	
	protected $page;
	
	public function __construct(IIterator $base, TMSFrontPage $page){
		parent::__construct($base);
		$this->page = $page;
	}
	
	public function Item(){
		$item = $this->iterator->Item();
		if ($item)
			return new TMSFrontPageItem($item, $this->page);
		return null;
	}
}

/**
 * @author dkrasilnikov@gmail.com
 * @property TMSUser $User
 * @property TMSFrontPageItem[] $MainMenu
 * @property TMSFrontPageItem[] $CatalogMenu
 * @property string $SearchUrl
 * @property string $ProfileUrl
 * @property string $RegisterUrl
 * @property string $AuthUrl
 * @property string $CartUrl
 * @property string $OrderUrl
 * @property string $CartSum
 * @property string $LogoutUrl
 * 
 */
abstract class TMSFrontPage extends TIntrinsicPage {
/**
 * @var TCart
 */	
	protected $_ioc_cart_;
/**
 * @var TCMSCategoryModel
 */	
	protected $_ioc_categories_model_;	
/**
 * @var TCMSPageModel
 */	
	protected $_ioc_pages_model_;
	
/**
 * @var ICaptchaProvider
 */	
	protected $_ioc_captcha_provider_;
	
	protected $_conf_captcha_name_;
	
	private $_main_menu_ = null;
	
	protected function getCategoryId($id){
		return is_numeric($id)?$id:$this->_slug_to_id($id,$this->CategoriesModel);
	}
	
	protected function getPageId($id){
		return is_numeric($id)?$id:$this->_slug_to_id($id,$this->PagesModel);
	}
	
	private function _slug_to_id($id, TCandyModel $model){
		$items = $model->GetList(new TListOptions(array(new TFilterOption('Slug', TConditionType::C_EQUAL, $id))));
		foreach ($items as $item){
			return $item->ItemId();
		}
		return null;
	}
	
	public function IsParentItem(TMSFrontPageItem $item){
		$path = $this->Path();
		foreach ($path as $p)
			if ($item->ClassName() == $p->ClassName() && $p->ItemId() == $item->ItemId())
				return true;
		return false;
	}
		
	protected function categoryContents($slug){
		$result = array();
		$category_id = null;
		if ($slug)
			$category_id = $this->getCategoryId($slug);

		if ($category_id || is_null($slug)){
			$categories = new TMSFrontPageItemIterator($this->CategoriesModel->GetContents($category_id,true,new TListOptions(array(new TFilterOption('IsPublished', TConditionType::C_EQUAL, true),new TFilterOption('Language', TConditionType::C_EQUAL, $this->Application()->Language)),array(new TSortingOption('OrderNumber')))),$this);
			$pages = new TMSFrontPageItemIterator($this->PagesModel->GetList(new TListOptions(array(new TFilterOption('Categories',TConditionType::C_EQUAL,$category_id),new TFilterOption('IsPublished', TConditionType::C_EQUAL, true),new TFilterOption('Language', TConditionType::C_EQUAL, $this->Application()->Language)))),$this);
			foreach ($categories as $c) $result[] = $c;
			foreach ($pages as $p) $result[] = $p;
		}
		return new TArrayIterator($result);
	}
	
	public function CategoryPages($slug){
		return $this->categoryContents($slug);
	}
	
	public function MenuItems($menu){	
		return $this->categoryContents($this->Service()->MenuSlug($menu));
	}
	
	public function PageItem($slug){
		return $this->PagesModel->GetItem($this->getPageId($slug));
	}
	
	public function CategoryItem($slug){
		return $this->CategoriesModel->GetItem($this->getCategoryId($slug));
	}
	
	protected function getPageCategory(IItem $page){
		foreach ($page->Categories as $cat){
			return $cat;
			break;
		}
		return null;
	}
	
	protected function getCategoryPath(IItem $category, &$result){
		if (!$this->Service()->IsMenu($category->Slug)){
			$result[] = new TMSFrontPageItem($category,$this);
			$p = $category->Container();
			while ($p && !$this->Service()->IsMenu($p->Slug)){
				$result[] = new TMSFrontPageItem($p,$this);
				$p = $p->Container();
			}
		}
	}
	
	protected function getNestedPagePath(IItem $page, &$result){
		if ($p = $page->AgregationContainer()){
			$result[] = new TMSFrontPageItem($p, $this);
			$this->getNestedPagePath($p, $result);
		} else if ($category = $this->getPageCategory($page))
			$this->getCategoryPath($category, $result);
	}	
	
	public function __get($nm){
		switch ($nm){
			case 'CaptchaUrl':return $this->Url(null,'Captcha');break;
			case 'CartUrl':return $this->service->CartUrl();break;
			case 'User':{ 
				$u = $this->service->Acl->CurrentUser();
				if (($u instanceof TMSUser) && ($u->Roles & TMSRole::CLIENT))
					return $u;
				return null;	
			}break;
			case 'MainMenu':{
				if (!is_array($this->_main_menu_))
					$this->_main_menu_ = $this->categoryContents($this->service->MainMenuRoot);
				return $this->_main_menu_;
			}break;
			case 'CatalogMenu':{
				return new TMSFrontPageItemIterator($this->CategoriesModel->GetContents($this->getCategoryId($this->service->CatalogRoot),false,new TListOptions(array(new TFilterOption('IsPublished', TConditionType::C_EQUAL, true),new TFilterOption('Language', TConditionType::C_EQUAL, $this->Application()->Language)),array(new TSortingOption('OrderNumber')))),$this);
			}break;
			case 'SearchUrl':return $this->service->SearchUrl();break;
			case 'ProfileUrl':return $this->service->ProfileUrl();break;
			case 'RegisterUrl':return $this->service->RegisterUrl();break;
			case 'DeliveryUrl':return $this->service->DeliveryUrl();break;
			case 'AuthUrl':return $this->service->AuthUrl();break;
			case 'CartUrl':return $this->service->CartUrl();break;
			case 'OrderUrl':return $this->service->OrderUrl();break;
			case 'CartSum':return ($this->Cart instanceof TCart)?$this->Cart->TotalSum():0;break;
			case 'CartCount':return ($this->Cart instanceof TCart)?$this->Cart->TotalCount():0;break;
			case 'LogoutUrl':return $this->Url(null,'Logout');break;
			case 'ShopSettingsMap':return $this->_settings_map_;break;
			default:{
				if ($this->Service()->ShopSettings)
					if ($v = $this->Service()->ShopSettings->GetValue($nm))
						return $v;
				return parent::__get($nm);
			}break;
		}
	}
	
	public function __set($nm,$value){
		switch ($nm){
			case 'ShopSettingsMap':$this->_settings_map_ = TConvertions::ConvertToArray($value,array(';','='),array(false,true));break;
			default:parent::__set($nm,$value);break;
		}
	}
	
	public function http_Captcha(){
		$this->CaptchaProvider->SendCaptcha($this->_conf_captcha_name_?$this->_conf_captcha_name_:$this->Name());
	}
	
	protected final function checkCaptcha($captcha){
		if (!$this->CaptchaProvider->CheckCaptcha($this->_conf_captcha_name_?$this->_conf_captcha_name_:$this->Name(), $captcha))
			throw new TExposableException('Неверная капча!');		
	}
	
	public function ItemUrl(IItem $item){
		return $this->service->ItemNavigationUrl($item);
	}
	
	public function http_Logout(){
		$this->service->ACL()->Logout();
	}
	
	public function http_Buy($product,$quantaty = 1){
		if ($this->Cart instanceof TCart){
			$this->Cart->AddPosition($product, $quantaty);
			if ($this->request->IsAjax){
				echo json_encode(array("count"=>$this->Cart->TotalCount(),"amount"=>$this->Cart->TotalSum()));
				die;
			}
		}
	}
	
	public function http_SetCartQuantaty($product,$quantaty = 1){
		if ($this->Cart instanceof TCart){
			$this->Cart->SetQuantaty($product, $quantaty);
			if ($this->request->IsAjax){
				echo json_encode(array("count"=>$this->Cart->TotalCount(),"amount"=>$this->Cart->TotalSum()));
				die;
			}
		}
	}
	
	public function http_CartReset(){
		if ($this->Cart instanceof TCart){
			$this->Cart->MakeEmpty();
			if ($this->request->IsAjax){
				echo json_encode(array("count"=>$this->Cart->TotalCount(),"amount"=>$this->Cart->TotalSum()));
				die;
			}
		}
	}
	
	public function SubItems(){return array();}
	
	public function SubCategories(){return array();}
	
	public function Path(){return array();}

	public function Keywords(){return '';}
	
	public function Description(){return '';}
	
	public function Title(){
		if ($title = parent::Title())
			return $title;
		if ($this->Service()->ShopSettings)
			if ($title = $this->Service()->ShopSettings->GetValue('DefaultTitle'))
				return $title;
	}	
}